package com.feo.kpler

import android.annotation.SuppressLint
import android.app.Application
import com.feo.kpler.videocache.HttpProxyCacheServer

object HttpMediaCacheServer {

    private var cacheServer: HttpProxyCacheServer? = null
    fun getProxy(): HttpProxyCacheServer? {
        if (cacheServer == null) {
            cacheServer = newProxy()
        }
        return cacheServer
    }

    private fun newProxy(): HttpProxyCacheServer? {
        val application = getApplicationByReflection() ?: return null
        return HttpProxyCacheServer.Builder(application)
            .cacheDirectory(FKerVideoCacheUtils.getVideoCacheDir(application))
            .build()
    }

    @SuppressLint("PrivateApi")
    private fun getApplicationByReflection(): Application? {
        try {
            return Class.forName("android.app.ActivityThread")
                .getMethod("currentApplication")
                .invoke(null) as Application
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            return Class.forName("android.app.AppGlobals")
                .getMethod("getInitialApplication")
                .invoke(null) as Application
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun cacheVideo(url: String?) {
        if (url.isNullOrEmpty()) {
            return
        }
        getProxy()?.let {
            it.registerCacheListener({ p0, p1, p2 -> }, url)
        }

    }

}